package controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import entity.MsgResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import entity.User;
import service.UserService;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/register")
    public String register() {
        return "system/register/register";
    }

    @RequestMapping("/login")
    public String login() {
        return "system/login/login";
    }

    @RequestMapping("/admin/admin_user_add")
    public String admin_user_add() {
        return "user/admin/admin_user_add";
    }

    @RequestMapping("/admin/admin_user_update")
    public String admin_user_update() {
        return "user/admin/admin_user_update";
    }

    @RequestMapping("/admin/purchaser_lst")
    public String purchaser_list() {
        return "user/admin/purchaser_list";
    }

    @RequestMapping("/admin/seller_list")
    public String seller_list() {
        return "user/admin/seller_list";
    }

    @RequestMapping("/admin/user_list")
    public String user_list() {
        return "user/admin/user_list";
    }

    @RequestMapping("/system/error")
    public String error() {
        return "system/error";
    }


    /**
     * 登录
     *
     * @param user               用户实体
     * @param httpServletRequest httpServletRequest
     * @return modelAndView
     */
    // 接收登录表单请求
    @RequestMapping("/doLogin")
    public ModelAndView doLogin(User user, HttpServletRequest httpServletRequest) {
        User flag = userService.login(user.getUser_name(), user.getPassword());
        ModelAndView modelAndView = new ModelAndView();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (flag != null) {
            if (flag.getRole() == 0) {
                modelAndView.setViewName("user/admin/admin");
                List<User> list = userService.showUser();
                modelAndView.addObject("list", list);
                modelAndView.addObject("current", dateFormat.format(new Date()));
                HttpSession session = httpServletRequest.getSession();
                session.setAttribute("user_name", flag.getUser_name());
                session.setAttribute("password", flag.getPassword());
                session.setAttribute("role", flag.getRole());
                session.setAttribute("id", flag.getUser_id());
            } else if (flag.getRole() == 1) {
                modelAndView.setViewName("user/purchaser/purchaserHome");
                List<User> list = userService.showUser();
                modelAndView.addObject("list", list);
                modelAndView.addObject("current", dateFormat.format(new Date()));
                HttpSession session = httpServletRequest.getSession();
                session.setAttribute("user_name", flag.getUser_name());
                session.setAttribute("password", flag.getPassword());
                session.setAttribute("role", flag.getRole());
                session.setAttribute("id", flag.getUser_id());
            } else {
                modelAndView.setViewName("user/seller/sellerHome");
                List<User> list = userService.showUser();
                modelAndView.addObject("list", list);
                modelAndView.addObject("current", dateFormat.format(new Date()));
                HttpSession session = httpServletRequest.getSession();
                session.setAttribute("user_name", flag.getUser_name());
                session.setAttribute("password", flag.getPassword());
                session.setAttribute("role", flag.getRole());
                session.setAttribute("id", flag.getUser_id());
            }
        } else {
            modelAndView.setViewName("system/login/login");
            modelAndView.addObject("current", dateFormat.format(new Date()));
        }
        return modelAndView;
    }

    /**
     * 清除Session
     *
     * @param httpServletRequest httpServletRequest
     * @return 登录页
     */
    @RequestMapping("/clearSession")
    public String clear(HttpServletRequest httpServletRequest) {
        HttpSession session = httpServletRequest.getSession();
        session.invalidate();
        return "system/login/login";
    }

    /**
     * 用户展示
     *
     * @return 用户列表页面
     */
    // 接收登录表单请求
    @RequestMapping("/doList")
    public ModelAndView doList() {
        ModelAndView modelAndView = new ModelAndView();
        List<User> user = userService.showUser();
        modelAndView.setViewName("user/admin/user_list");
        modelAndView.addObject("list", user);
        System.out.println(user);
        return modelAndView;
    }

    /**
     * 采购员展示
     *
     * @return 采购员列表页面
     */
    // 接收登录表单请求
    @RequestMapping("/doListOfPurchaser")
    public ModelAndView doListOfPurchaser() {
        ModelAndView modelAndView = new ModelAndView();
        List<User> purchaser = userService.showPurchaser();
        modelAndView.setViewName("user/admin/purchaser_list");
        modelAndView.addObject("list", purchaser);
        System.out.println(purchaser);
        return modelAndView;
    }

    /**
     * 销售员展示
     *
     * @return 销售员列表页面
     */
    // 接收登录表单请求
    @RequestMapping("/doListOfSeller")
    public ModelAndView doListOfSeller() {
        ModelAndView modelAndView = new ModelAndView();
        List<User> seller = userService.showSeller();
        modelAndView.setViewName("user/admin/seller_list");
        modelAndView.addObject("list", seller);
        System.out.println(seller);
        return modelAndView;
    }

    // 接收注册表单请求
    @RequestMapping("/doRegister")
    public ModelAndView doRegister(HttpServletRequest httpServletRequest) throws ParseException {
        SimpleDateFormat queueDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = queueDateFormat.format(new Date());
        Date createtime = queueDateFormat.parse(time);
        ModelAndView modelAndView = new ModelAndView();
        String user_name = httpServletRequest.getParameter("user_name");
        String password = httpServletRequest.getParameter("password");
        int role = Integer.parseInt(httpServletRequest.getParameter("role"));
        String birth = httpServletRequest.getParameter("birth");
        int sex = Integer.parseInt(httpServletRequest.getParameter("sex"));
        String phone = httpServletRequest.getParameter("phone");

        boolean success = userService.register(user_name, password, role, sex, phone, birth, createtime);

        if (success) {
            if (role == 0) {
                modelAndView.setViewName("user/admin/admin");
                List<User> list = userService.showUser();
                modelAndView.addObject("list", list);
                modelAndView.addObject("current", createtime);
                HttpSession session = httpServletRequest.getSession();
                session.setAttribute("user_name", user_name);
                session.setAttribute("password", password);
                session.setAttribute("role", role);
            } else if (role == 1) {
                modelAndView.setViewName("user/purchaser/purchaserHome");
                List<User> list = userService.showUser();
                modelAndView.addObject("list", list);
                modelAndView.addObject("current", createtime);
                HttpSession session = httpServletRequest.getSession();
                session.setAttribute("user_name", user_name);
                session.setAttribute("password", password);
                session.setAttribute("role", role);
            } else {
                modelAndView.setViewName("user/seller/sellerHome");
                List<User> list = userService.showUser();
                modelAndView.addObject("list", list);
                modelAndView.addObject("current", createtime);
                HttpSession session = httpServletRequest.getSession();
                session.setAttribute("user_name", user_name);
                session.setAttribute("password", password);
                session.setAttribute("role", role);
            }
        } else {
            modelAndView.setViewName("system/register/register");
        }
        return modelAndView;
    }

    // 接收批量注册表单请求
    @RequestMapping("/doAjaxRegisterInBatches")
    @ResponseBody
    public MsgResult doRegisterInBatches(@RequestBody List<User> users) throws ParseException {
        SimpleDateFormat queueDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = queueDateFormat.format(new Date());
        Date createTime = queueDateFormat.parse(time);
        MsgResult msgResult = new MsgResult();
        try {
            for (User user : users) {
                System.out.println("user" + user.toString());
                userService.register(user.getUser_name(), user.getPassword(), user.getRole(), user.getSex(), user.getPhone(),
                        user.getBirth(), createTime);
            }
            msgResult.setFlag(1);
            msgResult.setMsg("批量新增成功");
        } catch (Exception e) {
            msgResult.setFlag(0);
            msgResult.setMsg("批量新增失败");
            msgResult.setContent(e.getMessage());
        }

        return msgResult;
    }

    /**
     * 单个用户删除
     *
     * @param id 用户编号
     * @return 视图重定向至用户列表
     */
    // 接收删除请求
    @RequestMapping("/doDelete")
    public ModelAndView doDelete(int id) {
        boolean result = userService.deleteUser(id);
        if (result) {
            System.out.println("删除成功");
        } else {
            System.out.println("删除失败");
        }
        return new ModelAndView("redirect:/doList");
    }

    /**
     * 用户批量删除
     *
     * @param ids id集合
     * @return 视图重定向至用户列表
     */
    @RequestMapping("/doDeleteInBatches")
    public ModelAndView doDeleteInBatches(Integer[] ids) {
        ModelAndView modelAndView = new ModelAndView();
        System.out.println(ids);
        User user = new User();
        for (Integer id : ids) {
            user.setUser_id(id);
            boolean result = userService.deleteUser(user.getUser_id());
            System.out.println("successfully get user:" + id);
            if (result) {
                modelAndView.addObject("user", user);
                modelAndView.setViewName("user/list");
                System.out.println("successfully delete user:" + id);
            } else {
                System.out.println("fail to delete user:" + id);
            }
        }
        return new ModelAndView("redirect:/doList");
    }

    /**
     * 用户修改id获取
     *
     * @return 转到修改页
     */

    // 接收修改id
    @RequestMapping("/doUpdateId")
    public ModelAndView doUpdateId(HttpServletRequest request) {
        String id = request.getParameter("id");
        User user = userService.selectUserById(Integer.parseInt(id));
        request.setAttribute("user", user);
        System.out.println("xiugai" + id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("list", user);
        modelAndView.setViewName("user/admin/admin_user_update");
        return modelAndView;
    }

    /**
     * 用户修改
     *
     * @return 视图重定向至用户列表
     */
    // 接收修改请求
    @RequestMapping("/doUpdate")
    public ModelAndView doUpdate(User param) {
        ModelAndView modelAndView = new ModelAndView();
        User user = new User();
        user.setUser_id(param.getUser_id());
        user.setUser_name(param.getUser_name());
        user.setPassword(param.getPassword());
        user.setSex(param.getSex());
        user.setBirth(param.getBirth());
        user.setRole(param.getRole());
        user.setPhone(param.getPhone());
        System.out.println("xiugaizhixing" + user);
        boolean flag = userService.updateUser(user);
        if (flag) {
            System.out.println("xgzx--" + flag);
            modelAndView.addObject("list", user);
            modelAndView.setViewName("redirect:/doList");
        } else {
            System.out.println("修改失败");
        }
        return modelAndView;
    }
}
